package com.dongdongshop.mq;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dongdongshop.mapper.TbSeckillGoodsMapper;
import com.dongdongshop.mapper.TbSeckillOrderMapper;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbSeckillOrder;
import com.dongdongshop.utils.IdWorker;
import com.dongdongshop.utils.RedisKey;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@RocketMQMessageListener(consumerGroup = "seckill_group",topic = "seckill_topic")
@Component
public class SeckillOrderConsumer implements RocketMQListener<String> {

    @Autowired
    private IdWorker idWorker;
    @Resource
    private TbSeckillOrderMapper seckillOrderMapper;
    @Resource
    private TbSeckillGoodsMapper seckillGoodsMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void onMessage(String o) {
        JSONObject json = JSONUtil.parseObj(o);
        Object userId = json.get("userId");
        Object seckillId = json.get("seckillId");
        Long sid = Long.valueOf(seckillId.toString());
        // 生成订单
        TbSeckillGoods goods = seckillGoodsMapper.selectByPrimaryKey(sid);
        TbSeckillOrder order = new TbSeckillOrder();
        long orderId = idWorker.nextId();
        order.setStatus("0");  // 默认未支付
        order.setCreateTime(new Date());
        order.setMoney(goods.getCostPrice()); // 下单金额
        order.setSeckillId(sid);
        order.setUserId(userId.toString());
        order.setId(orderId);
        seckillOrderMapper.insertSelective(order);

        // 下单成功之后, 将订单的 id 缓存到redis 中
        redisTemplate.opsForHash().put(RedisKey.ORDERIDS,userId.toString(),String.valueOf(orderId));
    }
}
